package com.cskaoyan.exception;

import com.cskaoyan.bean.BaseRespVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author stone
 * @date 2022/11/17 16:30
 */
//@Component
public class CustomHandlerExceptionResolver implements HandlerExceptionResolver {
    @SneakyThrows
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler, Exception ex) {
        //可以返回ModelAndView,也可以响应Json， → JavaEE的方式
        String message = ex.getMessage();
        if (ex instanceof NumberFormatException) {
            //特殊的业务
        }
        // jackson工具类转换引用类型对象为json字符串
        BaseRespVo respVo = BaseRespVo.fail("HandlerExceptionResolver:" + message);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(respVo);


        response.getWriter().println(json);

        return null;
    }
}
